import os
import csv
import numpy
from   marketdatautils import downloadQuoteData
from   matplotlib.dates import num2date
from   matplotlib.dates import datestr2num
import matplotlib.pyplot as plt
from   techsignal import *
import datetime
from   config import WORKDIR, DATADIR

def test_downloadData():
    ''' download data for all the component stocks in the DJI index '''
        
    os.chdir(WORKDIR)
        
    with open('%s/DJI.csv'%data_prefix, 'rb') as csvfile:
        tickers = csv.reader(csvfile, delimiter='\t')
        for tk in tickers:
            res = downloadQuoteData( tk[0], start_date = '2000-1-1', end_date ='2013-11-20' )
            f = open( '%s/%s.csv'%(data_prefix, tk[0]), 'w' )
            w = csv.writer( f )
            w.writerows( res )
            f.close()

def makeplotdata( data, lag ):
    idx = numpy.arange( len(data) ) + lag
    return numpy.transpose( numpy.vstack( (idx, data) ) )
    
def test_techsignal( symbol ):
    ''' test plot of tech signals '''
    
    os.chdir(WORKDIR)
    
    data = numpy.loadtxt( '%s/%s.csv'%(DATADIR, symbol), \
                          delimiter = ',', usecols=(0,4), skiprows = 1, \
                          converters = { 0: datestr2num } )
    
    data = numpy.transpose( data )
    lag1 = 2
    lag2 = 2

    data_sma = SMA( data, lag1 ) 
    data_ema = EMA( data, lag2 )
        
    fig = plt.figure()
    ax = fig.add_subplot( 1,1,1 )
    plt.plot( data[0], data[1], 'r-', data_sma[0], data_sma[1], 'g-', data_ema[0], data_ema[1], 'b-' )
    ax.set_title( 'test plot' )
    
    xt = ax.get_xticks()
    new_xticks = [ datetime.date.isoformat(num2date(d)) for d in xt ]
    ax.set_xticklabels(new_xticks, rotation=45, horizontalalignment='right')
    plt.show()
        

def main():
    
    test_techsignal( 'AAPL' )
    
if __name__ == "__main__":
    main()
    
    
    
    